#include "head.h"
#include <iostream>
#include <sys/socket.h>

using std::cout;
using std::endl;

int main()
{
    //1. 创建监听套接字
    int sfd = socket(AF_INET, SOCK_STREAM, 0);
    cout << "sfd:" << sfd << endl;
    ERROR_CHECK(sfd, -1, "socket");
    
    //2. 服务器绑定网络地址
    struct sockaddr_in serveraddr;
    memset(&serveraddr, 0, sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(8000);
    serveraddr.sin_addr.s_addr = inet_addr("192.168.30.129");

    int ret = bind(sfd, 
        (const struct sockaddr*)&serveraddr, sizeof(serveraddr));
    ERROR_CHECK(ret, -1, "bind");

    //3. 进行监听
    ret = listen(sfd, 1);
    cout << "server is listening.\n";

    while(1) {
        //4. 接收客户端的请求
        cout << "enter while loop" << endl;
        //accept函数默认情况下是一个阻塞式函数
        //如果没有新的客户端连接到来时，就阻塞
        //如果有了新的客户端连接，就会从全连接队列上取一下套接字
        int newFd = accept(sfd, NULL, NULL);
        cout << "111, newFd:" << newFd << endl;
        ERROR_CHECK(newFd, -1, "accept");

        //5. 与客户端进行通信
        char buff[1024] = "hello,client";
        send(newFd, buff, strlen(buff), 0);
        memset(buff, 0, sizeof(buff));//清空用户态缓冲区
        
        //recv函数不知道接下来会接收多少数据，所以第三个参数
        //指定的是buff的整个长度
        recv(newFd, buff, sizeof(buff), 0);
        cout << "recv from client:" << buff << endl;
    }

    close(sfd);
    return 0;
}
